https://github.com/micropython/micropython-lib/tree/master/umqtt.simple
https://github.com/micropython/micropython-lib/tree/master/umqtt.robust
https://github.com/cclai999/micropython-lab/blob/master/remote_contorl_via_mqtt.py
http://www.hivemq.com/blog/mqtt-essentials-part2-publish-subscribe
http://www.hivemq.com/blog/mqtt-essentials-part-6-mqtt-quality-of-service-levels
http://www.hivemq.com/blog/mqtt-essentials-part-5-mqtt-topics-best-practices
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718072
https://github.com/cclai999/micropython-lab/blob/master/remote_contorl_via_mqtt.py
Start a Mosquitto container first. For example:
codes\_demo\1_start_broker.sh
to start a Mosquitto container on Raspberry Pi.mqtt_config\mqtt
.allow_anonymous true
in mqtt_config\mqtt\config\mosquitto.conf
to allow anonymous client.This script only work with MicroPython.
Using MQTT client module for MicroPython.
In [ ]:
import time
import config
import worker_config
host = config.BROKER_HOST
port = config.HUB_PORT
topic_root = "test"
client_id = worker_config.WORKER_NAME
auth = {'username': config.USERNAME,
'password': config.PASSWORD}
qos_level = config.QOS_LEVEL
import simple as mqtt
# import robust as mqtt
client = mqtt.MQTTClient(client_id = client_id,
server = host,
port = port,
user = config.USERNAME,
password = config.PASSWORD,
keepalive = 60,
ssl = False, ssl_params = {})
topic = topic_root
msg = 'last will'
client.set_last_will(topic, msg, retain = False, qos = 1)
client.connect(clean_session = True)
client.ping()
# _________________________________________
def on_message(topic, msg):
print('Message topic: {}, payload: {}'.format(topic, str(msg)))
# print('Message:\n{}\n'.format(msg.__dict__))
client.set_callback(on_message)
client.subscribe(topic_root, qos = 1)
# client.subscribe("$SYS/broker/messages/#", qos = 1)
# client.subscribe("$SYS/broker/clients/connected", qos = 1)
client.subscribe('$SYS/broker/log/#', qos = 1)
topic = topic_root
msg = 'Hello world'
client.publish(topic, msg, retain = False, qos = 1)
while True:
time.sleep(1)
client.wait_msg()
client.check_msg()
In [ ]:
client.disconnect()
client = None